'use strict';
import React, {Component} from 'react';
import {
    View,
    Text,
    TextInput,
    TouchableOpacity,
    Platform,
    Image,
    StyleSheet,
    ActivityIndicator
} from 'react-native';
import ToolBar from '../Components/ToolBar';
import ImagePicker from 'react-native-image-picker';
import Toast from '../Utils/toast';
import Global from '../Commom/GlobalConst';

const width = Global.Const.size.width;
import FoundAPIService from '../Commom/FoundAPIService';
const styles = StyleSheet.create({
    choiceImgBox: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        alignItems: 'center',
        padding: 15,
        backgroundColor: 'white',
        marginBottom: 10
    },
    image: {
        width: (width - 50) / 4,
        height: (width - 50) / 4,
        marginRight: 5,
        marginTop: 5,
    },
    inputContentBox: {
        padding: 15,
        backgroundColor: 'white',
        marginBottom: 1,
        fontSize: 14,
        height: 150,
        lineHeight: 25,
        color: Global.FontColor.DarkGray
    },
    inputTitle: {
        color: 'black',
        flex: 1,
        fontSize: 14,
        textAlign: 'right',
    },
    titleBox: {
        height: 45,
        padding: 15,
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 1,
        backgroundColor: 'white',
        marginBottom: 10,
        paddingTop: 0,
        paddingBottom: 0,
    }
});

/**
 * 发起游记
 */
class InitiatedTravels extends Component {

    constructor(props) {
        super(props);
        this.state = {
            inputTitle:'',
            inputContent:'',
            choiceImages: [],
            content: '',
            title: '',
            imagePath: [],
            number: [],
            submitting:false,
        }
    }

    choiceImage() {
        if (this.state.imagePath.length == 8) {
            Toast.show("最多选择8张图片");
            return;
        }
        let options = {
            title: '请选择图片',
            cancelButtonTitle: '取消',
            chooseFromLibraryButtonTitle: '从手机相册选择',
            takePhotoButtonTitle: '从相机拍照获取',
            allowsEditing: true,
            maxWidth: 750,
            maxHeight: 1280,
            quality:0.75,
        };
        ImagePicker.showImagePicker(options, (res) => {
            if (res.didCancel) {
                Toast.show('已取消选择');
            } else if (res.error) {
                Toast.show('选择图片错误');
            } else if (res.customButton) {

            } else {
                let source = '';
                let path = '';
                if (Platform.OS === 'ios') {
                    source = {uri: res.uri.replace('file://', ''), isStatic: true};
                    path = res.uri.replace('file://', '');
                } else {
                    source = {uri: res.uri, isStatic: true};
                    path = res.path;
                }
                this.setState({
                    choiceImages: this.state.choiceImages.concat(source),
                    imagePath: this.state.imagePath.concat(path),
                });
            }
        });
    }


    initiatedTravel() {
        TextInput.State.blurTextInput(TextInput.State.currentlyFocusedField());
        if (this.state.inputTitle.length==0) {
            Toast.show("请输入游玩标题");
            return;
        }
        if (this.state.inputContent.length==0) {
            Toast.show("请输入问题内容");
            return;
        }
        this.setState({
            submitting: true,
        });
        FoundAPIService.initiatedTravel(Global.Const.token, Global.Const.registeredId, this.state.inputTitle, this.state.inputContent).then((ret)=> {
            if (this.state.imagePath.length > 0) {
                for (var i = 0; i < this.state.imagePath.length; i++) {
                    FoundAPIService.updateImg(Global.Const.token, Global.Const.registeredId, ret, this.state.imagePath[i]).then((ret)=> {
                        this.setState({
                            number: this.state.number.concat(i),
                        });
                        if (this.state.number.length == this.state.imagePath.length) {
                            this.setState({
                                submitting: false,
                            });
                            Toast.show("发布成功");
                            console.log('上传图片了');
                            this.props.navigator.pop();
                        }
                    }).catch((err)=> {
                        this.setState({
                            submitting: false,
                        });
                    });
                }
            } else {
                this.setState({
                    submitting: false,
                });
                Toast.show("发布成功");
                console.log('没有上传图片');
                this.props.navigator.pop();
            }

        }).catch((err)=> {
            this.setState({
                submitting: false,
            });
        });
    }

    render() {
        return (
            <TouchableOpacity activeOpacity={1} style={{flex: 1}} onPress={() => {
                TextInput.State.blurTextInput(TextInput.State.currentlyFocusedField())
            }}>
                <View style={{
                    flex: 1,
                    backgroundColor: '#F2F3F5'
                }}>
                    <ToolBar
                        leftFunc={() => this.props.navigator.pop()}
                        title="发起游记"
                        rightFunc={()=> {
                           this.initiatedTravel();
                        }}
                        rightImage={require('../../Image/release_icon.png')}
                    />
                    <View style={styles.titleBox}>
                        <Text>标题</Text>
                        <TextInput
                            placeholder={'请输入标题'}
                            maxLength={20}
                            value={this.state.inputTitle}
                            onChangeText={inputTitle => this.setState({ inputTitle })}
                            style={styles.inputTitle}
                            underlineColorAndroid={'rgba(0,0,0,0)'}
                        />
                    </View>
                    <Text style={{
                        padding: 15,
                        backgroundColor: 'white',
                        marginBottom: 1,
                    }}>说明</Text>
                    <TextInput
                        placeholder={'请输入内容'}
                        multiline={true}
                        maxLength={500}
                        value={this.state.inputContent}
                        onChangeText={inputContent => this.setState({ inputContent })}
                        underlineColorAndroid={'rgba(0,0,0,0)'}
                        textAlignVertical="top"
                        style={styles.inputContentBox}
                    />
                    <View style={styles.choiceImgBox}>
                        {
                            this.state.choiceImages ?
                                this.state.choiceImages.map((item, index) => {
                                    return (
                                        <Image
                                            key={'image' + index}
                                            style={styles.image}
                                            source={item}
                                        />
                                    )
                                }) : null
                        }
                        <TouchableOpacity
                            onPress={() => this.choiceImage()}
                        >
                            <Image style={styles.image} source={require('../../Image/photo_input.png')}/>
                        </TouchableOpacity>
                    </View>
                </View>
                {this.state.submitting ? <View
                    style={{position: 'absolute',top:0,left:0,width:Global.Const.size.width,height:Global.Const.size.height,backgroundColor:null,alignItems:'center',justifyContent:'center'}}>
                    <View
                        style={{backgroundColor:'#333333',borderRadius:5, alignItems: 'center',justifyContent: 'center',width:80,height:80}}>
                        <ActivityIndicator
                            animating={this.state.animating}
                            style={{ alignItems: 'center',justifyContent: 'center'}}
                            size="large"/>
                        <Text style={{color:'white'}}>正在提交</Text>
                    </View>
                </View> : null}
            </TouchableOpacity>
        )
    }
}

export default InitiatedTravels;